#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libpq-fe.h>

int main() {
    int    nFields;
    int      i,j;

    // 连接到数据库
    PGconn * conn = PQconnectdb("xxx");
    if (PQstatus(conn) != CONNECTION_OK) {
        fprintf(stderr, "无法连接到数据库: %s", PQerrorMessage(conn));
        PQfinish(conn);
        return 1;
    }

    // 执行查询语句
    PGresult *res = PQexec(conn, "SELECT n.nspname as \"Schema\",c.relname as \"Name\",CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'I' THEN 'global partition index' WHEN 'S' THEN 'sequence' WHEN 'L' THEN 'large sequence' WHEN 'f' THEN 'foreign table' WHEN 'm' THEN 'materialized view'  WHEN 'e' THEN 'stream' WHEN 'o' THEN 'contview' END as \"Type\",pg_catalog.pg_get_userbyid(c.relowner) as \"Owner\",c.reloptions as \"Storage\" FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('S','L','') AND n.nspname <> 'pg_catalog' AND n.nspname <> 'db4ai' AND n.nspname <> 'information_schema' AND n.nspname !~ '^pg_toast' AND c.relname not like 'matviewmap\\_%' AND c.relname not like 'mlog\\_%' AND pg_catalog.pg_table_is_visible(c.oid) ORDER BY 1,2");
    if (PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr, "查询失败: %s", PQerrorMessage(conn));
        PQclear(res);
        PQfinish(conn);
        return 1;
    }

        // 获取结果集中的行数
    int rows = PQntuples(res);
    nFields = PQnfields(res);
    /* 打印行 */
    char result[1024];
    const char *sql="sequence";
    for (i = 0; i < PQntuples(res); i++){
        for (j = 0; j < nFields; j++){
            if (strcmp(PQgetvalue(res, i, j), sql) == 0) {
                // 获取你需要的两个字段的列索引，假设需要 column2 和 column4
                int column_index1 = PQfnumber(res, "\"Schema\"");
                int column_index2 = PQfnumber(res, "\"Name\"");
                if (column_index1 == -1 || column_index2 == -1) {
                    fprintf(stderr, "未找到指定的列\n");
                    PQclear(res);
                    PQfinish(conn);
                    return 1;
                }

                // 遍历结果集，获取所需两个字段的值
                for (int i = 0; i < rows; i++) {
                const char *value1 = PQgetvalue(res, i, column_index1);
                const char *value2 = PQgetvalue(res, i, column_index2);
                printf("第 %d 行: Schema 的值为 %s, Name 的值为 %s\n", i + 1, value1, value2);
                printf("gs_dump -U daihu -p 7654 dh -s -t %s.%s  -f %s.%s.sql\n", value1, value2,value1, value2);

    }
            }
        
        }
    }


    // 释放结果集和关闭数据库连接
    PQclear(res);
    PQfinish(conn);

    return 0;
}